package com.fintech.pangu.security.authentication.token.impl;

import com.fintech.pangu.commons.api.BaseResponse;
import com.fintech.pangu.commons.util.HttpUtil;
import com.fintech.pangu.security.authentication.token.AuthenticationToken;
import com.fintech.pangu.security.authentication.token.AuthenticationTokenResponder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证Token响应默认处理
 * 包含cookie返回、response返回等常用做法，不满足可自行实现
 */
@Setter
@Getter
@Slf4j
public class DefaultAuthenticationTokenResponder implements AuthenticationTokenResponder {

    /**
     * token返回类型（cookie、response）
     */
    private String tokenReturnType;

    /**
     * token以cookie形式返回时的domain
     */
    private String domain;

    /**
     * token以cookie形式返回时的path
     */
    private String path;

    /**
     * token以cookie形式返回时的maxAge
     */
    private int maxAge;

    private boolean secure;


    @Override
    public void handlingResponse(AuthenticationToken authenticationToken, HttpServletResponse response) throws IOException {
        if(StringUtils.hasText(tokenReturnType)){
            // 1、以cookie形式返回token
            if("cookie".equals(tokenReturnType)){
                Cookie cookie = new Cookie("pangu_auth_token", authenticationToken.getValue());
                cookie.setPath(path);
                cookie.setDomain(domain);
                cookie.setMaxAge(getMaxAge(authenticationToken));
                cookie.setHttpOnly(true);
                cookie.setSecure(secure);
                response.addCookie(cookie);

                // json格式成功response
                HttpUtil.responseForJson(response, BaseResponse.success());
            }
            // 2、以响应形式返回token
            else if("response".equals(tokenReturnType)){
                HttpUtil.responseForJson(response, new BaseResponse(authenticationToken.getValue()));
            }
        }
    }


    /**
     * 获取cookie最大使用期限
     * @param token
     * @return
     */
    private int getMaxAge(AuthenticationToken token){
        // 如果token有值，是登录场景，按照配置返回maxAge
        if(token!=null && StringUtils.hasText(token.getValue())){
            return maxAge;
        }
        // 如果token为空串，是登出场景，返回0
        else if(token!=null && StringUtils.isEmpty(token.getValue())){
            return 0;
        }
        // token==null，也返回0
        else {
            return 0;
        }
    }

}
